package sentinel.demo02.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sentinel.demo02.service.HelloService;

@RestController
public class HelloController {
    @Autowired
    private HelloService helloService;
    @GetMapping("/hello")
    public String sayHi(String name){
        //将helloService.sayHi(name) 看成是资源来定义
        String result=null;
        //设置资源的入口
        Entry entry=null;
        //想要调用保护的资源 sayHi业务方法 必须先进入entry
        //如果进入entry的过程是违反规则的,进入就失败了,异常抛出,方法不调用
        //能够正常进入entry 允许调用资源
        try{
            //给entry赋值 entry定义一个名字,叫做资源名称
            entry= SphU.entry("sayHi01");
            result=helloService.sayHi(name);
        }catch (BlockException e){
            //entry赋值失败 表示违反规则 ,抛出BlockException
            //调用目标资源失败 降级逻辑
            result="服务资源被降级处理了,entry赋值失败,sorry "+name;
        }finally{
            //释放entry资源记录
            if (entry!=null)entry.exit();
        }
        return result;
    }
}
